import './TeacherVideoList.scss'
import TeacherVideoItem from './components/TeacherVideoItem/TeacherVideoItem';
import { addVideoAPI,deleteVideoAPI, changeVideoInfoAPI } from '@/apis/teacher';
import { useEffect, useState, useRef } from 'react';
import { DeleteOutlined, FlagFilled, PlusOutlined } from '@ant-design/icons';
import { Button, Modal, ConfigProvider, Input, message, Empty } from 'antd';
import { fetchGetVideoList } from '@/store/modules/teacher';
import { useDispatch, useSelector } from 'react-redux';

export default function TeacherVideoList() {
    const dispatch = useDispatch();
    const videoFile = useRef(null);
    const { user_status } = useSelector(state => state.user);
    const { videoList } = useSelector(state => state.teacher);
    const [checkList, setCheckList] = useState([]);
    const [hasChecked, setHasChecked] = useState(false);
    const [checkedItemNum, setCheckedItemNum] = useState(0);
    const [allChecked, setAllChecked] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [loading, setLoading] = useState(false);
    const [newVideoName, setNewVideoName] = useState('');
    const [isChangeModalOpen,setIsChangeModalOpne] = useState(false);
    const [curVideoId,setCurVideoId] = useState('');

    const showModal = () => {
        setIsModalOpen(true);
    };

    const showChangeModal = (video_id) => {
        setCurVideoId(video_id);
        setIsChangeModalOpne(true);
    }

    function toBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result.split(',')[1]);
            reader.onerror = error => reject(error);
        });
    }

    const handleAddVideo = async () => {
        setLoading(true);
        const file = videoFile.current.files[0];
        console.log(file);
        if(!file) return;
        const base64Video = await toBase64(file);
        console.log(base64Video);
        console.log(newVideoName);

        const res = await addVideoAPI({
            class_id:user_status.class_id,
            video_name:`${newVideoName}.mp4`,
            video:base64Video
        },user_status.token);
        console.log(res);
        setNewVideoName('');
        window.location.reload();
        message.success('添加成功');
        setLoading(false);
        setIsModalOpen(false);
    };

    const handleDeleteVideoList = async () => {
        const data = [];
        checkList.forEach((ele,index)=>{
            if(ele) data.push({
                class_id:user_status.class_id,
                video_id:videoList[index].video_id
            })
        })
        const res = await deleteVideoAPI(data,user_status.token);
        console.log(res);
        if(res.data[0].success) {
            message.success(res.data[0].message);
            window.location.reload();
        }else {
            message.error(res.data[0].message);
        }
        
    }

    const handleCancelAddVideo = () => {
        setIsModalOpen(false);
    };


    const handleChangeVideo = async () => {
        const res = await changeVideoInfoAPI({
            class_id:user_status.class_id,
            video_id:curVideoId,
            video_name:newVideoName
        },user_status.token);
        console.log(res.data.message);
        setNewVideoName('');
        setIsChangeModalOpne(false);
        dispatch(fetchGetVideoList(user_status.class_id,user_status.token));
        // window.location.reload();
    }

    const handleCancelChangeVideo = () => {
        setIsChangeModalOpne(false);
    }



    // 当组件渲染完成时执行一次
    useEffect(() => {

        const getVideoList = async function () {
                await dispatch(fetchGetVideoList(user_status.class_id,user_status.token));
        }

        getVideoList();
    }, [])


    
    useEffect(() => {
        if (videoList.length !== 0) {
            setCheckList(Array(videoList.length).fill(false));
            // console.log(checkList);
        }
    }, [videoList]);


    useEffect(() => {
        if (checkList.length !== 0) {
            setHasChecked(checkList.reduce((a, b) => a || b), false);
            setCheckedItemNum(checkList.reduce((a, b) => b ? ++a : a, 0));
            setAllChecked(checkList.reduce((a, b) => a && b), true);
        }
    }, [checkList])


    const handleAllCheck = (e) => {
        setCheckList(checkList.map(() => e.target.checked))
    }

    const handleCancel = () => {
        setCheckList(checkList.map(() => false));
    }


    return (
        <div className='TeacherVideoList'>
            <nav
                style={{
                    height: hasChecked ? '40px' : '0'
                }}
            >
                <div className='all-check'>
                    <input
                        type='checkbox'
                        onChange={handleAllCheck}
                        checked={allChecked}
                        id='allcheckbox'
                    />
                    <label htmlFor='allcheckbox'>全选</label>
                    <div className='divide-line'></div>
                    <span>已选择{checkedItemNum}个视频</span>
                </div>
                <div className='delet-video'>
                    <button onClick={handleDeleteVideoList}><DeleteOutlined /> 删除</button>
                    <div className='divide-line'></div>
                    <button onClick={handleCancel}>取消</button>
                </div>
            </nav>
            <main>
                {videoList.length === 0 || 
                ( videoList[0].success?
                    videoList.map(ele =>
                    <TeacherVideoItem
                        key={ele.id}
                        info={ele}
                        ifChecked={checkList[ele.id]}
                        onCheck={(key) => {
                            setCheckList(checkList.map((ele, index) => index === key ? !ele : ele));
                        }}
                        showChangeModal={showChangeModal}
                    />
                ):<Empty 
                className='empty'
                image={Empty.PRESENTED_IMAGE_SIMPLE} 
                description={
                    <span>
                        课程还没有添加视频，点击右下角的图标添加
                    </span>
                }
            />
                )
            }
            </main>
            <ConfigProvider
                theme={{
                    token: {
                        // Seed Token，影响范围大
                        colorPrimary: '#2486b9',
                        borderRadius: 5,

                        // 派生变量，影响范围小
                        // colorBgContainer: '#f6ffed',
                    },
                }}
            >
                <Button
                    type="primary"
                    onClick={showModal}
                    className='add-video'
                >
                    <PlusOutlined />
                </Button>
                <Modal
                    title={<h3>新增视频</h3>}
                    open={isModalOpen}
                    onCancel={handleCancelAddVideo}
                    footer={[
                        <Button key="back" onClick={handleCancelAddVideo}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={loading} onClick={handleAddVideo}>
                            确定
                        </Button>
                    ]}
                    centered
                    width={480}
                >
                    <label htmlFor='newvideoname'>请输入新增视频的名称</label>
                    <Input id='newvideoname' onInput={function (e) { setNewVideoName(e.target.value) }} value={newVideoName} />
                    <br />
                    <br />
                    <label htmlFor='videofile'>请选择要添加的视频文件(.mp4)</label>
                    <input id='videofile' type='file' ref={videoFile} accept='.mp4'/>
                </Modal>
                <Modal
                    title={<h3>视频重命名</h3>}
                    open={isChangeModalOpen}
                    onCancel={handleCancelChangeVideo}
                    footer={[
                        <Button key="back" onClick={handleCancelChangeVideo}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={loading} onClick={handleChangeVideo}>
                            确定
                        </Button>
                    ]}
                    centered
                    width={480}
                >
                    <label htmlFor='newvideoname'>请输入新的视频名称</label>
                    <Input id='newvideoname' onInput={function (e) { setNewVideoName(e.target.value) }} value={newVideoName} />
                </Modal>
            </ConfigProvider>
        </div>
    )
}